#!/usr/bin/env python
# coding=UTF-8
'''
@Author: 赵天天
@LastEditors: 赵天天
@email: dayday_1996@163.com
@Descripttion: 任务管理下发任务
@Date: 2019-04-28 17:31:10
@LastEditTime: 2019-04-29 10:07:34
'''
import json
import warnings
import urllib3
from flask import Blueprint, g
from lib import auth
from psycopg2 import connect
from lib.record import recodelog
from psycopg2.extras import RealDictCursor

from config import config
# from lib.funcs import sync_to_anguan
from lib.validform import V, ValidateForm

urllib3.disable_warnings()
warnings.filterwarnings("ignore")

app = Blueprint(__name__ + "_app", __name__)


@app.before_request
def setupdb():
    g.conn = connect(**config.DatabaseConfig.siem)
    g.cursor = g.conn.cursor(cursor_factory=RealDictCursor)


@app.teardown_request
def unsetdb(exception):
    if g.cursor:
        g.cursor.close()
        g.cursor = None
    if g.conn:
        g.conn.close()
        g.conn = None


# 告警处置下发--获取下发数据(提交处置成功以后的回调接口，将下发的处置信息发送给合作方)
@app.route('/api/task/assignment', methods=['POST'])
@auth.permission("task")
def task_assignment():
    try:
        form = ValidateForm(
            task_id=['任务id', V.required()]
        )
        (flag, data) = form.validate()
        print data
        if not flag:
            data['status'] = 'fail'
            return json.dumps(data)
        assign = {}
        g.cursor.execute("""select a.task_id as "taskId",
                                    a.task_name as "taskName",
                                    a.tasktype ::character varying(16) as "taskType",
                                    b.timerange as "timeRange",
                                    f.securityLevel ::character varying(16) as "securityLevel",
                                    a.datatype as "dataType",
                                    e.beaconrule as "beaconRule"
                                from (
                                    select task_id ,
                                        task_name,
                                        'according_monitor' as tasktype,
                                        case task_type when '1' then 'depth_analysis'
                                                when '2' then 'flow'
                                                when '3' then 'audit'
                                                when '4' then 'vulnerability' end as  datatype
                                    from h_survey_task_info ) as a
                                left join (select 
                                                row_to_json(a) as timerange
                                            from (
                                                select d2t(start_time) as "startTime",
                                                    d2t(request_return_time) as "endTime"
                                                from h_survey_task_info
                                                where task_id = %s
                                                ) as a) as b
                                on 1=1 

                                left join (    select json_object_agg(element_type, dd) as beaconrule
                                                from (
                                                    select task_id,
                                                        element_type,
                                                        array_agg(element_name)  as dd
                                                    from (select t.element_type,
                                                            task_id,
                                                            element_name
                                                        from (values('ip'),('url'),('domian'), ('protocol'),('threadName'), ('md5'), ('cve') ) as t(element_type)
                                                        left join (
                                                            select task_id ,
                                                                case element_type 
                                                                when 'URL' then 'url'
                                                                when 'domain' then 'domain'
                                                                when 'comprotocals' then 'protocol'
                                                                when 'threatname' then 'threadName' 
                                                                when 'node' then 'ip'
                                                                when 'MD5' then 'md5' 
                                                                when 'vulnername' then 'cve' end element_type,
                                                                element_name
                                                            from h_survey_task_element
                                                            where element_type <> 'safelevel' and task_id = %s
                                                        ) as a
                                                        on a.element_type = t.element_type
                                                    ) as a
                                                    group by element_type,
                                                        task_id 
                                                ) as a ) as e
                                on 1=1
                                left join (     select task_id ,
                                            element_name as securitylevel 
                                        from h_survey_task_element
                                        where element_type = 'safelevel') as f
                                on a.task_id = f.task_id
                                where a.task_id = %s
                                """ % (data["task_id"], data["task_id"], data["task_id"]))
        res = g.cursor.fetchone()
        assign = res
        # 目标项 指定系统 指定设备 
        g.cursor.execute("""with tb as (
                                    select split_part(aim_url, '/', 1) as agency_id, 
                                           split_part(aim_url, '/', 2) as info_sys_id, 
                                           split_part(aim_url, '/', 3) as sys_node_id
                                        from h_survey_task_aim
                                    where task_id = '%s'
                                )
                                select  agency_id,
                                        agency_name, 
                                array_agg(distinct info_sys_name) info_sys_name,
                                array_agg(distinct sys_node_name) sys_node_name
                                            from 
                                            (select b.agency_id,
                                                    b.agency_name, 
                                                    c.info_sys_name, 
                                                    d.sys_node_name 
                                                from sys_agency_info b
                                                inner join h_information_system c on b.agency_id = c.agency_id and c.state = '1'
                                                inner join h_system_node d on c.info_sys_id = d.info_sys_id and d.state = '1'
                                                inner join (select * from tb where tb.sys_node_id is not null) a on b.agency_id = a.agency_id and c.info_sys_id = a.info_sys_id and d.sys_node_id = a.sys_node_id
                                            union
                                            select b.agency_id,
                                                b.agency_name, 
                                                c.info_sys_name, 
                                                d.sys_node_name 
                                from sys_agency_info b
                                inner join h_information_system c on b.agency_id = c.agency_id and b.state = '1'
                                inner join h_system_node d on c.info_sys_id = d.info_sys_id and d.state = '1'
                                inner join (select * from tb where tb.sys_node_id = '') a on b.agency_id = a.agency_id and c.info_sys_id = a.info_sys_id) f
                                            group by f.agency_name,
                                                    agency_id
                                            """ % (data["task_id"]))
        aim = g.cursor.fetchall()
        for item in aim:
            item['agency_id']
            assign['sys_obj'] = item['info_sys_name']
            assign['dev_obj'] = item['sys_node_name']
            # print  assign        
        # sync_to_anguan(module='任务管理', opreaing='任务下发', url='http://192.168.111.10:8080/api/CACSMP/commandrecive', method='POST', data=res)
        return json.dumps({"status": "success", "data": res})
    except Exception, e:
        return json.dumps({"status": "except", 'msg': '查询失败', 'warn': str(e)})


# 新增任务
@app.route('/api/task/addtask', methods=['POST'])
@auth.permission("task")
def addtask_assignment(_currUser):
    try:
        form = ValidateForm(task_msg=['协查任务信息表', V.optional()],
                            task_target=['协查任务目标表', V.optional()],
                            task_element=['协查任务元素表', V.optional()])
        (flag, data) = form.validate()
        if not flag:
            data['status'] = 'fail'
            return json.dumps(data)
        task_msg = eval(data['task_msg'])
        task_target = eval(data['task_target'])
        task_element = eval(data['task_element'])
        element_id = task_msg['element_id']
        if element_id == 0:
            element_id = 'NULL'
        r_person = str(_currUser['user']['person_id'])
        g.cursor.execute(""" insert into h_survey_task_info 
                                    (
                                    task_name,
                                    element_id,
                                    task_state,
                                    task_type,
                                    start_time,
                                    request_return_time,
                                    r_person,
                                    r_time
                                    ) 
                                    values(%(task_name)s,
                                            """ + str(element_id) + """  ,  
                                            '1',
                                            %(task_type)s,
                                            %(start_time)s,
                                            %(request_return_time)s,
                                            """ + r_person + """,
                                            now())
                                    returning task_id,
                                            task_name,
                                            element_id,
                                            case task_state when '1' then '已下发' 
                                                            when '2' then '已完成' 
                                                            when '3' then '超时未反馈' end  as task_state,
                                            case task_type when '1' then '深度分析任务' 
                                                           when '2' then '流量监测任务' 
                                                           when '3' then '审计监测任务' 
                                                           when '4' then '脆弱性监测任务' end  as  task_type,
                                            start_time,
                                            request_return_time,
                                            r_time    """, (task_msg))
        g.conn.commit()
        returndata = g.cursor.fetchone()
        task_id = returndata['task_id']
        rem = {"任务名称": "%s" % returndata['task_name'],
               "任务状态": "%s" % returndata['task_state'],
               "任务类型": "%s" % returndata['task_type'],
               "任务开始时间": "%s" % returndata['start_time'],
               "任务结束时间": "%s" % returndata['request_return_time'],
               "创建人": "%s" % str(_currUser['user']['person_name']),
               "创建时间": "%s" % returndata['r_time']}
        auth.logsync(_currUser, {"function": "任务管理", "type": "新增", "remark": "新增任务" + recodelog(rem)})
        for target in task_target:
            g.cursor.execute("""insert into h_survey_task_aim 
                                (task_id,
                                 aim_id,
                                 aim_name,
                                 aim_type,
                                 aim_url,
                                 issue_state,
                                 issue_time,
                                 feedback_state,
                                 feedback_time,
                                 r_person,
                                 r_time
                                 )
                                values( """ + str(task_id) + """ ,
                                    %(aim_id)s,
                                    %(aim_name)s,
                                    %(aim_type)s,
                                    %(aim_url)s,
                                    '1',
                                    now(),
                                    '0',
                                    now(),
                                    """ + r_person + """,
                                    now() )  """, (target))
            g.conn.commit()
        for element in task_element:                         
            g.cursor.execute("""insert into h_survey_task_element 
                                        (   task_id,
                                            element_type,
                                            element_name,
                                            r_person,
                                            r_time
                                        )
                            values( """ + str(task_id) + """ ,
                                %(element_type)s,
                                %(element_name)s,
                                """ + r_person + """,
                                now())
                                 """, (element))
            g.conn.commit()
        return json.dumps({
            "status": "success",
            "msg": "添加成功",
            "task_id": task_id 
        })
    except Exception as e:
        return json.dumps({"status": "except", 'msg': '添加失败', 'warn': str(e)})